/**
 * Copyright [2010] [Tom Cramer (TomCee)]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package nl.tomcee.fontselector;

import java.awt.Component;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import net.miginfocom.swing.MigLayout;

/**
 * Creates a dialog to let users select a font.
 * @author Tom
 *
 * @since 1.8
 * <pre>
 * restructured the java file
 * added 'about' context-menu
 * restructured the 'preview' section
 * </pre>
 * @since 1.7
 * <pre>
 * Font names now show in their own fontstyle (codesnip from D.Ekholm)
 *
 * Added a constructor for providing your own fontlist
 * you can now call:
 * FontSelector(string[]) or FontSelector(string[],int,int,int)
 * example:
 *
 * String[] webSafeFonts={"Arial","Bookman Old Style","Comic Sans MS","Courier",
 * "Courier New","Garamond","Georgia","Impact","Lucida Console","Lucida Sans Unicode",
 * "MS Sans Serif","MS Serif","Palatino Linotype","Tahoma","Times New Roman","Trebuchet MS","Verdana"};
 * FontSelector fs=new FontSelector(webSafeFonts);
 *
 * <pre>
 */
public class FontSelector extends javax.swing.JDialog {

    private final String version = "1.8";
    private String[] fontFaces = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
    private String[] fontSizes = {"8", "9", "10", "11", "12", "13", "14", "16", "18",
        "20", "24", "28", "32", "36", "40", "48", "60", "72", "96"};
    private String[] fontStyles = {"plain", "bold", "italic", "bolditalic"};
    /**
     * param to check if <b>ok</b> or <b>cancel</b> is pressed
     */
    public boolean okPressed;
    private JList fontNameList;
    private final int i1;
    private final int i2;
    private final int i3;
    private String fontName;
    private Integer fontSize;
    private JScrollPane spFontNameList;
    private JList fontStyleList;
    private JScrollPane spFontStyleList;
    private JList fontSizeList;
    private Font selectedFont;
    private JScrollPane spFontSizeList;
    private JButton okButton;
    private JButton cancelButton;
    private JPanel panelA;
    private String settings;
    private JLabel preview;

    /** Creates new form FontSelector */
    public FontSelector() {
        i1 = 0;
        i2 = 0;
        i3 = 5;
        initComponents();
        act();
    }

    /**
     * creates a developer defined form FontSelector.<br>
     * The values can be obtained as tooltiptext in the
     * form window left to the -ok-button,<br>
     * or with the <b>getSettings()</b> method.
     * @see #getSettings()
     * @param p1 sets the default index for the font name list
     * @param p2 sets the default index for the font style list
     * @param p3 sets the default index for the font size list
     */
    public FontSelector(int p1, int p2, int p3) {
        i1 = p1;
        i2 = p2;
        i3 = p3;
        initComponents();
        act();
    }

    /**
     * creates a default form FontSelector with a developer defined font list
     * @param s the font list
     */
    public FontSelector(String[] s) {
        i1 = 0;
        i2 = 0;
        i3 = 5;
        fontFaces = s;
        initComponents();
        act();
    }

    /**
     * <pre>
     * creates a developer defined form FontSelector,
     * with a developer defined font list.
     * The values can be obtained as tooltiptext in the
     * form window left to the -ok-button,
     * or with the <b>getSettings()</b> method.
     * @see #getSettings()
     * @param s the font list
     * @param p1 sets the default index for the font name list
     * @param p2 sets the default index for the font style list
     * @param p3 sets the default index for the font size list
     * </pre>
     */
    public FontSelector(String[] s, int p1, int p2, int p3) {
        i1 = p1;
        i2 = p2;
        i3 = p3;
        fontFaces = s;
        initComponents();
        act();
    }

// <editor-fold defaultstate="collapsed" desc="methods">
    /**
     *
     * @return selected font
     */
    public Font getSelectedFont() {
        return selectedFont;
    }

    /**
     *
     * @return fontname
     */
    public String getFontName() {
        return fontName;
    }

    /**
     *
     * @return fontsize
     */
    public Integer getFontSize() {
        return fontSize;
    }

    /**
     *
     * @return fontstyle
     */
    public String getFontStyle() {
        return (String) fontStyleList.getSelectedValue();
    }

    /**
     *
     * @return returns a string with index values:<br>
     * (fontNameList, fontStyleList, fontSizeList)
     */
    public String getSettings() {
        settings = String.valueOf(fontNameList.getSelectedIndex())
                + "," + String.valueOf(fontStyleList.getSelectedIndex())
                + "," + String.valueOf(fontSizeList.getSelectedIndex());
        return settings;
    }

    private void act() {
        fontName = (String) fontNameList.getSelectedValue();
        fontSize = Integer.valueOf((String) fontSizeList.getSelectedValue());
        selectedFont = new Font(fontName, fontStyleList.getSelectedIndex(), fontSize);
        preview.setText(getFontName());
        preview.setFont(selectedFont);
        panelA.setToolTipText(getSettings());
        pack();
    }
    ListCellRenderer renderer = new DefaultListCellRenderer() {

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            label.setFont(new Font(value.toString(), Font.PLAIN, 13));
            label.setToolTipText(value.toString());
            return label;
        }
    };// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="InitComponents">

    private void initComponents() {
        setModal(true);
        setTitle("FontSelector");
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setLocationByPlatform(true);
        addWindowListener(new java.awt.event.WindowAdapter() {

            @Override
            public void windowClosing(java.awt.event.WindowEvent evt) {
                okPressed = false;
                dispose();
            }
        });

        // other components go here:
        fontNameList = new JList(fontFaces);
        fontNameList.setCellRenderer(renderer);
        fontNameList.setLayoutOrientation(JList.VERTICAL);
        fontNameList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        fontNameList.setSelectedIndex(i1);
        fontNameList.addMouseListener(new java.awt.event.MouseAdapter() {

            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                act();
            }
        });
        spFontNameList = new JScrollPane(fontNameList);

        fontStyleList = new JList(fontStyles);
        fontStyleList.setLayoutOrientation(JList.VERTICAL);
        fontStyleList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        fontStyleList.setSelectedIndex(i2);
        fontStyleList.addMouseListener(new java.awt.event.MouseAdapter() {

            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                act();
            }
        });
        spFontStyleList = new JScrollPane(fontStyleList);

        fontSizeList = new JList(fontSizes);
        fontSizeList.setLayoutOrientation(JList.VERTICAL);
        fontSizeList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        fontSizeList.setSelectedIndex(i3);
        fontSizeList.addMouseListener(new java.awt.event.MouseAdapter() {

            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                act();
            }
        });
        spFontSizeList = new JScrollPane(fontSizeList);

        preview = new JLabel();

        okButton = new javax.swing.JButton("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okPressed = true;
                dispose();
            }
        });
        cancelButton = new javax.swing.JButton("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okPressed = false;
                dispose();
            }
        });

        createPanelA();
        getContentPane().add(panelA, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="panels">

    private void createPanelA() {
        panelA = new JPanel() {

            {
                addMouseListener(new java.awt.event.MouseAdapter() {

                    @Override
                    public void mouseClicked(java.awt.event.MouseEvent evt) {
                        aboutMouseAction(evt);
                    }

                    @Override
                    public void mouseReleased(java.awt.event.MouseEvent evt) {
                        aboutMouseAction(evt);
                    }
                });
                setLayout(new MigLayout());
                add(new JLabel("Font:"));
                add(new JLabel("Style:"));
                add(new JLabel("Size:"), "wrap");
                add(spFontNameList, "width 220:220:,height 180:180:");
                add(spFontStyleList, "width 90:90:,height 180:180:");
                add(spFontSizeList, "width 60:60:,height 180:180:,wrap 10");
                add(preview, "width 250:370:,span,wrap 15");
                add(okButton, "sg 1, span,split, alignx right, tag ok");
                add(cancelButton, "sg 1, tag cancel");
            }
        };
    }
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="aboutMouse Action">

    private void aboutMouseAction(java.awt.event.MouseEvent evt) {
        if (evt.isPopupTrigger()) {
            JOptionPane.showMessageDialog(rootPane, "FontSelector\nversion: "
                    + version
                    + "\nauthor: Tom", "about:", JOptionPane.INFORMATION_MESSAGE);
        }
    }// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="main">

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new FontSelector().setVisible(true);
            }
        });
    }// </editor-fold>
}//end of class

